package com.tanhua.admin.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.FreezeMapper;
import com.tanhua.admin.service.AnalysisService;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.UserInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 *     1.类交给容器管理
 *     2.编写方法（定时执行的业务方法）
 */
@Component
public class AnalysisTask {

    @Autowired
    private AnalysisService analysisService;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FreezeMapper freezeMapper;

    /**
     * 方法：没有参数，没有返回值
     * 业务：业务功能（打印系统时间）
     * 注解：定义时间规则
     */
    @Scheduled(cron = "* 0/30 * * * ?")
    public void analysis() {
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("当前时间："+now);

        //核心业务：将日志表的数据计算之后，写入到统计表中
        try {
            analysisService.analysis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 每小时查询冻结表是否有用户要被解冻
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void unfreezeTheAccount () {
        //被冻结的用户id集合
        List<Long> ids = new ArrayList<>();

        //当前时间
        Date now = new Date();
        //查询用户解冻时间条件
        QueryWrapper<Freeze> qw = new QueryWrapper<>();
        //获取所有被冻结的用户
        List<UserInfo> list =  userInfoApi.findByFreezeUser();
        for (UserInfo userInfo : list) {
            //遍历取出id
            Long userId = userInfo.getId();
            ids.add(userId);

            //把每个id去冻结表查出解冻时间
            qw.eq("user_id", userId);
            Freeze freeze = freezeMapper.selectOne(qw);
            Date unfreezeTime = freeze.getUnfreezeTime();
            if (unfreezeTime == null) {
                continue;
            }
            //比较是否需要解冻
            boolean after = now.after(unfreezeTime);
            if (after) { //ture代表当前时间大 需要解封
                userInfo.setUserStatus("1"); //用户状态,1为正常，2为冻结
                userInfoApi.update(userInfo);
                freeze.setUnfreezeTime(null);
                freeze.setReasonsForThawing("到期自动解冻");
            }
        }
        System.out.println("处理完毕需要解冻的用户");
    }
}
